<template>
  <WujieVue
    :key="name"
    width="100%"
    height="100%"
    :name="name"
    :url="appUrl"
    :sync="appInfo.sync"
    :alive="appInfo.alive"
    :props="microProps"
  ></WujieVue>
</template>

<script setup>
import wujie from 'wujie-vue3'
import { getSubMap } from '@/wujie/config'
import { useRoute, useRouter } from 'vue-router'
import { computed, watch, reactive } from 'vue'
import { useSystem } from '@/store/system'
import { getLocalData, paramsToUrl } from '@common'
const props = defineProps({
  name: {
    type: String,
    required: true
  }
})
const name = props.name
const appInfo = getSubMap(name)
const route = useRoute()
const router = useRouter()
const appUrl = computed(() => {
  return appInfo.url + '#' + route.fullPath
})
const system = useSystem()
const microProps = reactive({ routers: [], userInfo: {} })
const replaceComponent = (e) => {
  e.component = e.componentName
  delete e.componentName
  if (e.children) {
    e.children.forEach(replaceComponent)
  }
}
const microPropsChangeKey = computed(() => {
  return `${system.userInfo.userId}_${JSON.stringify(system.routers)}`
})
watch(
  microPropsChangeKey,
  () => {
    if (system.userInfo.userId && system.routers) {
      microProps.token = system.token
      microProps['tenant-id'] = getLocalData('tenant-id')
      microProps['channel'] = getLocalData('channel')
      const reg = new RegExp(`^https://${name}`, 'i')
      let routers = system.routers.filter((e) => reg.test(e.meta?.link || ''))
      routers = JSON.parse(JSON.stringify(routers))
      routers.forEach(replaceComponent)
      microProps.routers = routers
      microProps.userInfo = system.userInfo
      microProps.pushApp = (microName, { path, query }) => {
        const paramsUrl = paramsToUrl(query)
        const fullPath = paramsUrl ? `${path}?${paramsUrl}` : path
        router.push(fullPath)
        wujie.bus.$emit('main-sub-route', {
          appId: microName,
          data: fullPath
        })
      }
    }
  },
  {
    immediate: true,
    deep: true
  }
)
</script>
